package com.tiku.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tiku.common.ResultJson;
import com.tiku.controller.DTO.UserOrderDTO;
import com.tiku.entity.ProductSpecifications;
import com.tiku.entity.UserOrder;
import com.tiku.entity.UserOrderRelation;
import com.tiku.mapper.ProductSpecificationsMapper;
import com.tiku.mapper.UserOrderMapper;
import com.tiku.service.UserOrderRelationService;
import com.tiku.service.UserOrderService;
import com.tiku.service.UserPayTikuService;
import com.tiku.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
* @author Administrator
* @description 针对表【user_order】的数据库操作Service实现
* @createDate 2024-10-06 11:01:36
*/
@Service
public class UserOrderServiceImpl extends ServiceImpl<UserOrderMapper, UserOrder>
    implements UserOrderService {


    @Autowired
    private UserOrderMapper userOrderMapper;

    @Autowired
    private UserOrderRelationService userOrderRelationService;

    @Autowired
    private ProductSpecificationsMapper productSpecificationsMapper; // 添加依赖

    @Autowired
    private UserPayTikuService userPayTikuService;


    // 存储逻辑
    @Override
    public ResultJson addorder(List<ProductSpecifications> selectedSubjects) {
        String threadLocal = ThreadLocalUtil.getThreadLocal();
        Boolean isExist= userPayTikuService.getSpecFlag(threadLocal,selectedSubjects);

        if (isExist){
            return ResultJson.error("选择科目已购买");
        }
        // 创建一个订单实体
        UserOrder order = new UserOrder();

        // 生成订单编号
        String orderNumber = generateOrderNumber();
        order.setUserId(threadLocal);
        order.setUserQuestionTable(selectedSubjects.get(0).getSetMealId()); // 假设取第一个元素的 setMealId
        order.setOrderNumber(orderNumber);
        order.setOrderType("0");
        order.setCreateTime(new Date());

        // 假设使用第一个商品的 specid 获取价格
        // 你可能需要根据具体业务逻辑决定如何处理多个产品
        ProductSpecifications productSpec = productSpecificationsMapper.selectById(selectedSubjects.get(0).getSpecid());
        if (productSpec != null) {
            order.setMoney(productSpec.getDisPrice().multiply(BigDecimal.valueOf(selectedSubjects.size())).setScale(2, RoundingMode.HALF_UP)); // 设置 money 字段为查询到的 dis_price
        } else {
            return ResultJson.error("产品规格不存在");
        }

        // 存储 user_order 数据
        userOrderMapper.insert(order); // 保存到 user_order 表

        // 存储 user_order_relation 数据
        List<UserOrderRelation> relations = new ArrayList<>();
        for (ProductSpecifications spec : selectedSubjects) {
            UserOrderRelation relation = new UserOrderRelation();
            relation.setOrderNumber(orderNumber);
            relation.setSpecid(spec.getSpecid()); // 假设 getSpecid() 方法存在

            relations.add(relation);
        }
        userOrderRelationService.saveBatch(relations);
        // 保存到 user_order_relation 表
        return ResultJson.success(order.getOrderNumber());
    }

    @Override
    public ResultJson selectOrder(String orderId) {
        // 获取当前登录用户user_id
        String userId = ThreadLocalUtil.getThreadLocal();

        // 调用Mapper层的方法查询订单详情
        List<UserOrderDTO> orderDetails = userOrderMapper.selectOrderDetail(orderId, userId);

        if (orderDetails.isEmpty()) {
            return ResultJson.error("查询失败");
        }

        // 返回结果
        return ResultJson.success(orderDetails);
    }

    @Override
    public ResultJson selectOrders(String orderType) {
        // 获取当前登录用户user_id
        String userId = ThreadLocalUtil.getThreadLocal();

        // 调用Mapper层的方法查询订单详情
        List<UserOrderDTO> orderDetails = userOrderMapper.selectOrderDetails(userId,orderType);


        // 返回结果
        return ResultJson.success(orderDetails);
    }

    @Override
    public ResultJson activationCode(String activationCode) {

        if (Objects.equals(activationCode, "1667301172")){


            return ResultJson.success();
        }


        return ResultJson.error("无效激活码");
    }

    @Override
    public ResultJson delOrder(String orderId) {

        String userId = ThreadLocalUtil.getThreadLocal();
        int delete = userOrderMapper.delete(new LambdaQueryWrapper<UserOrder>().eq(UserOrder::getOrderNumber, orderId).eq(UserOrder::getUserId, userId));

        return delete>0?ResultJson.success():ResultJson.sysError();
    }


    // 生成订单编号的方法
    private String generateOrderNumber() {
        long timestamp = System.currentTimeMillis(); // 当前时间戳
        int randomNum = (int) (Math.random() * 10000); // 生成一个随机数
        return String.valueOf(timestamp) + String.valueOf(randomNum); // 组合为一个字符串
    }

}





